package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MemberDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.MedicalHistory;
import com.itheima.pojo.Member;
import com.itheima.pojo.MemberMsg;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author chencfgs
 * @date 2019-12-07 16:01
 */

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Override
    public Member findByTelephone(String telephone) {
        Member member = memberDao.findByTelephone(telephone);
        return member;
    }

    @Override
    public void add(Member member) {
        if (member.getPassword() != null) {
            member.setPassword(MD5Utils.md5(member.getPassword()));
        }
        memberDao.add(member);
    }


    @Override
    public void update(Member member) {
        memberDao.update(member);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //findPage赋值
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页助手自动查询
        PageHelper.startPage(currentPage, pageSize);
        if (queryString != null && queryString != "") {
            queryString = "%" + queryString + "%";
        }
        Page<Member> page = memberDao.findPage(queryString);
        //获取总页数和分页查询结果页面
        long total = page.getTotal();
        List<Member> rows = page.getResult();
        PageResult pageResult = new PageResult(total, rows);

        return pageResult;
    }

    /**
     * 后台添加member
     *
     * @param map
     */
    @Override
    public void add(Map<String, Object> map) {
        //分别封装三个pojo，Member、MedicalHistory、MemberMsg
        //封装会员动态信息
        MemberMsg memberMsg = MemberServiceImpl.packageMemberMsg(map);
        memberDao.addMemberMsg(memberMsg);
        int memberMsgId = memberMsg.getId();
        //封装会员病史
        MedicalHistory medicalHistory = MemberServiceImpl.packageMedicalHistory(map);
        memberDao.addMedicalHistory(medicalHistory);
        int medicalHistoryId = medicalHistory.getId();
        if (memberMsgId != 0 && medicalHistoryId != 0) {
            //封装会员主体信息
            Member member = MemberServiceImpl.packageMember(map);
            member.setMsgId(memberMsgId);
            member.setMhistoryId(medicalHistoryId);
            memberDao.addMember(member);
        }
    }

    /**
     * 通过memberId删除会员档案
     *
     * @param memberId
     */
    @Override
    public void deleteMember(Integer memberId) {
        //要删除会员档案 同时需要删除会员病历历史和基本信息
        Member member = memberDao.findOneById(memberId);
        if (member == null) {
            throw new RuntimeException();
        }
        //删除两张关联表
        memberDao.deleteMember_msgById(member.getMsgId());
        memberDao.deleteMedical_historyById(member.getMhistoryId());
        //删除主表
        memberDao.deleteMember(memberId);
    }


    /**
     * 批量删除member
     *
     * @param memberIds
     */
    @Override
    public void deleteMemberByIds(Integer[] memberIds) {
        //暂时不写
    }

    /**
     * 查询管理师
     * @param username
     * @return
     */
    @Override
    public List<String> findUsername(String username) {
        return memberDao.findUsername(username);
    }

    /**
     * 修改会员档案
     *
     * @param map
     */
    @Override
    public void editMember(Map<String, Object> map) {

        //分别封装三个pojo，Member、MedicalHistory、MemberMsg
        Member member = MemberServiceImpl.packageMember(map);
        member.setId(Integer.parseInt(map.get("id").toString()));

        MemberMsg memberMsg = MemberServiceImpl.packageMemberMsg(map);
        memberMsg.setId(Integer.parseInt(map.get("msgId").toString()));

        MedicalHistory medicalHistory = MemberServiceImpl.packageMedicalHistory(map);
        medicalHistory.setId(Integer.parseInt(map.get("mhistoryId").toString()));

        memberDao.updateMemberMsg(memberMsg);
        memberDao.updateMedicalHistory(medicalHistory);
        memberDao.updateMember(member);
    }

    //根据id查询会员信息
    @Override
    public Map<String, Object> findMemberById(Integer memberId) {
        Map<String, Object> map = new HashMap<>();
        //添加数据
        Member member = memberDao.findOneById(memberId);
        map.put("id", memberId);
        map.put("fileNumber", member.getFileNumber());
        map.put("name", member.getName());
        map.put("sex", member.getSex());
        map.put("idCard", member.getIdCard());
        map.put("phoneNumber", member.getPhoneNumber());
        map.put("regTime", member.getRegTime());
        map.put("password", member.getPassword());
        map.put("email", member.getEmail());
        map.put("birthday", member.getBirthday());
        map.put("remark", member.getRemark());
        map.put("nation", member.getNation());
        map.put("marriage", member.getMarriage());
        map.put("culture", member.getCulture());
        map.put("healthname", member.getHealthname());
        map.put("age", member.getAge());
        map.put("job", member.getJob());
        map.put("address", member.getAddress());
        map.put("status", member.getStatus());
        map.put("msgId", member.getMsgId());
        map.put("mhistoryId", member.getMhistoryId());

        //判断是否有从表,有就查询并添加
        if (member.getMsgId() != null) {
            MemberMsg memberMsg = memberDao.findMember_msgById(member.getMsgId());
            map.put("msgId", memberMsg.getId());
            map.put("height", memberMsg.getHeight());
            map.put("weight", memberMsg.getWeight());
            map.put("breathe", memberMsg.getBreathe());
            map.put("dbp", memberMsg.getDbp());
            map.put("systolicp", memberMsg.getSystolicp());
            map.put("heat", memberMsg.getHeat());
            map.put("waistline", memberMsg.getWaistline());
            map.put("hipline", memberMsg.getHipline());
            map.put("bmi", memberMsg.getBmi());
            map.put("oxyhemoglobin", memberMsg.getOxyhemoglobin());
        }
        if (member.getMhistoryId() != null) {
            MedicalHistory medicalHistory = memberDao.findMedical_historyById(member.getMhistoryId());
            map.put("historyId", medicalHistory.getId());
            map.put("previousHistory", medicalHistory.getPreviousHistory());
            map.put("familyHistory", medicalHistory.getFamilyHistory());
            map.put("allergy", medicalHistory.getAllergy());
            map.put("medicalHistory", medicalHistory.getMedicalHistory());
            map.put("chronicDisease", medicalHistory.getChronicDisease());
        }
        return map;
    }


    @Override
    public List<Integer> findMemberCountByMonth(List<String> month) {
        List<Integer> list = new ArrayList<>();
        for (String m : month) {
            m = m + ".31";
            Integer count = memberDao.findMemberCountBeforeDate(m);
            list.add(count);
        }
        return list;
    }

    //封装一个 会员信息对象
    public static MemberMsg packageMemberMsg(Map<String, Object> map) {

        MemberMsg memberMsg = new MemberMsg();

        if (map.get("height") != null) {
            memberMsg.setHeight(Double.parseDouble(map.get("height").toString()));
        }
        if (map.get("weight") != null) {
            memberMsg.setWeight(Double.parseDouble(map.get("weight").toString()));
        }
        if (map.get("dbp") != null) {
            memberMsg.setDbp(Double.parseDouble(map.get("dbp").toString()));
        }

        if (map.get("breathe") != null) {
            memberMsg.setBreathe(Double.parseDouble(map.get("breathe").toString()));
        }

        if (map.get("systolicp") != null) {
            memberMsg.setSystolicp(Double.parseDouble(map.get("systolicp").toString()));
        }

        if (map.get("heat") != null) {
            memberMsg.setHeat(Double.parseDouble(map.get("heat").toString()));
        }

        if (map.get("waistline") != null) {
            memberMsg.setWaistline(Double.parseDouble(map.get("waistline").toString()));
        }

        if (map.get("hipline") != null) {
            memberMsg.setHipline(Double.parseDouble(map.get("hipline").toString()));
        }

        if (map.get("bmi") != null) {
            memberMsg.setBmi((String) map.get("bmi"));
        }

        if (map.get("oxyhemoglobin") != null) {
            memberMsg.setOxyhemoglobin(Double.parseDouble(map.get("oxyhemoglobin").toString()));
        }
        return memberMsg;
    }


    //病史对象封装
    public static MedicalHistory packageMedicalHistory(Map<String, Object> map) {
        MedicalHistory medicalHistory = new MedicalHistory();
        if (map.get("allergy") != null) {
            medicalHistory.setAllergy((String) map.get("allergy"));
        }

        if (map.get("chronicDisease") != null) {
            medicalHistory.setChronicDisease((String) map.get("chronicDisease"));
        }

        if (map.get("familyHistory") != null) {
            medicalHistory.setFamilyHistory((String) map.get("familyHistory"));
        }

        if (map.get("medicalHistory") != null) {
            medicalHistory.setMedicalHistory((String) map.get("medicalHistory"));
        }

        if (map.get("previousHistory") != null) {
            medicalHistory.setPreviousHistory((String) map.get("previousHistory"));
        }

        return medicalHistory;
    }

    //封装前端对象
    public static Member packageMember(Map<String, Object> map) {
        Member member = new Member();
        if (map.get("fileNumber") != null) {
            member.setFileNumber((String) map.get("fileNumber"));
        }

        if (map.get("name") != null) {
            member.setName((String) map.get("name"));
        }

        if (map.get("sex") != null) {
            member.setSex((String) map.get("sex"));
        }

        if (map.get("idCard") != null) {
            member.setIdCard((String) map.get("idCard"));
        }

        if (map.get("phoneNumber") != null) {
            member.setPhoneNumber((String) map.get("phoneNumber"));
        }

        /*if (map.get("regTime") != null) {
            member.setRegTime((Date) map.get("regTime"));
        }*/
        if(map.get("regTime") == null){
            member.setRegTime(new Date());
        }

        if (map.get("password") != null) {
            member.setPassword((String) map.get("password"));
        }

        if (map.get("email") != null) {
            member.setEmail((String) map.get("email"));
        }

        if (map.get("birthday") != null) {
            member.setBirthday((Date) map.get("birthday"));
        }

        if (map.get("remark") != null) {
            member.setRemark((String) map.get("remark"));
        }

        if (map.get("nation") != null) {
            member.setNation((String) map.get("nation"));
        }

        if (map.get("marriage") != null) {
            member.setMarriage((String) map.get("marriage"));
        }

        if (map.get("culture") != null) {
            member.setCulture((String) map.get("culture"));
        }

        if (map.get("healthname") != null) {
            member.setHealthname((String) map.get("healthname"));
        }

        if (map.get("age") != null) {
            Integer.parseInt(map.get("age").toString());
        }

        if (map.get("job") != null) {
            member.setJob((String) map.get("job"));
        }

        if (map.get("address") != null) {
            member.setAddress((String) map.get("address"));
        }

        if (map.get("status") != null) {
            member.setStatus(Integer.parseInt((map.get("status")).toString()));
        }

        return member;
    }
}
